/* Note: this is at the same time valid JavaScript and C++. */

WT_DECLARE_WT_MEMBER
(HandleDrop, Wt::JavaScriptFunction, "HandleDrop",
function(evt)
{
  try
  {
//  Wt.WT.cancelEvent(evt, Wt.WT.CancelPropagate);
   evt.stopPropagation();
   evt.preventDefault();

   var files = evt.dataTransfer.files; // FileList object.
   if( files.length !== 1 )
     return;
   var uploadURL = null;
   try
   {
     //I think there should be a Wt.WT... call for the next line
     var sender = (evt && evt.target) || (window.event && window.event.srcElement);
     uploadURL = $('#'+sender.id).eq(0).data('UploadURL');
     if( !uploadURL ) return;
   }catch(e)
   {
     console.log("Caught error getting URL in HandleDrop");
     return;
   }

   var file  = files[0];
   var xhr = new XMLHttpRequest();
   xhr.open("POST", uploadURL, false);
   xhr.setRequestHeader("Content-type", "application/x-spectrum");
   xhr.setRequestHeader("Cache-Control", "no-cache");
   xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
   xhr.setRequestHeader("X-File-Name", file.name);
   xhr.send(file);

   var data = xhr.responseText;
   var status = xhr.status;
   if( status !== 200 && data )
     alert( data + "\nResponse code " + status );
  }catch(error)
  {
    console.log( "Error in HandleDrop" );
  }
}
);

WT_DECLARE_WT_MEMBER
(HandleDragEnter, Wt::JavaScriptFunction, "HandleDragEnter",
function(evt)
{
//      Wt.WT.cancelEvent(evt, Wt.WT.CancelPropagate);
  evt.stopPropagation();
  evt.preventDefault();
  evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
//     console.log("handleDragEnter - " );
}//function handleDragOver(evt)
);

WT_DECLARE_WT_MEMBER
(HandleDragExit, Wt::JavaScriptFunction, "HandleDragExit",
function(evt)
{
  evt.stopPropagation();
  evt.preventDefault();
}
);

WT_DECLARE_WT_MEMBER
(HandleDragOver, Wt::JavaScriptFunction, "HandleDragOver",
function (evt)
{
  evt.stopPropagation();
  evt.preventDefault();
}
);


WT_DECLARE_WT_MEMBER
(InitDragNDrop, Wt::JavaScriptFunction, "InitDragNDrop",
function(id,url)
{
  try
  {
    var el = Wt.WT.getElement(id);
    var jEl = $('#' + id );
    jEl.eq(0).data('UploadURL', url );
    el.addEventListener('dragenter', Wt.WT.HandleDragOver, false);
    el.addEventListener('dragexit', Wt.WT.HandleDragExit, false);
    el.addEventListener('dragover', Wt.WT.HandleDragOver, false);
    el.addEventListener('drop', Wt.WT.HandleDrop, false);
  }catch(e)
  {
    console.log('InitDragNDrop Error for id=' + is );
  }
}
);
